define(["constant", "handlebars", "site", "public"], function (Constant, Handlebars, site, Public) {
    var url = {
        list: 'manager/selectPersonalPublicList.do',
        ajaxqueryRegion: "manager/ajaxqueryRegion.do",
        selectAdminSalesman: "manager/selectAdminSalesman.do",
        updatePersonalfollow: "manager/updatePersonalfollow.do",
        selectOrderPageListByPid: "manager/selectOrderPageListByPid.do",
        selectProductALl: 'manager/selectProductALl.do',
        updatePersonalLocked: "manager/updatePersonalLocked.do",
        d_queryTraceLogsList: "manager/queryTraceLogsListByPersonalId.do",//查询日志
        e_insertTraceLogs: "manager/insertTraceLogs.do",// 新增日志
        f_deleteTraceLogs: "manager/deleteTraceLogs.do",//删除日志
        g_editTraceLogs: "manager/editTraceLogs.do"
    }

    var selectAdminData = {
        pageNum: 1
    }

    var edit_traceLog = {
        id: "",
        content: ""
    }

    var delect_ids = {
        ids: ""
    }

    var a = 'up';

    var block_list = {
        ids: "",
        locked: "",
        lockedContent: ""
    }

    var queryTraceLogsdata = {
        pageNum: "1",
        logs_type: "5",
        personal_id: ""
    }

    var udpateAdmin = {};

    //拉黑名单
    function block_list_fun() {
        site.send({
            url: url.updatePersonalLocked,
            //async:false
            data: block_list,
            callback: function (data) {
                var list = JSON.parse(data);

                if (list.type == 1) {
                    $('.blacklist').toggle();
                    Constant.fn.Message("T", list.msg);
                    pjaxReload()
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })
    }

    //新增和编辑弹框
    function newAndEditTraceLogWindow(state, content) {

        $(".add_trace_log_window").css("display", "block");
        if (state == 'new') {
            $(".newAndEditLog_title").text("新增客户跟踪日志")
            $(".newAndEditLog_content").html("<span style='color: red;'>*</span>新增的日志内容：")
            $(".add_trace_log_text").val('')


        }
        if (state == 'edit') {
            $(".add_trace_log_text").val(content)
            $(".newAndEditLog_title").text("编辑客户跟踪日志")
            $(".newAndEditLog_content").html("<span style='color: red;'>*</span>编辑的日志内容:")


        }
    }

    function cover_fun() {
        site.send({
            url: url.updatePersonalLocked,
            //async:false
            data: block_list,
            callback: function (data) {
                var list = JSON.parse(data);

                if (list.type == 1) {
                    $('.coverUsual_winBox').toggle();
                    Constant.fn.Message("T", list.msg);
                    pjaxReload()
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })
    }

    function delect_trace_log() {
        site.send({
            url: url.f_deleteTraceLogs,
            data: delect_ids,
            callback: function (data) {
                var list = JSON.parse(data);
                if (list.type == 1) {
                    Constant.fn.Message('T', list.msg)
                    queryTraceLogsList();
                } else {
                    Constant.fn.Message('F', list.msg)
                }
            }
        })
    }

    // 更换业务员
    function changeAdminFun(admin_id) {
        site.send({
            url: url.selectAdminSalesman,
            data: selectAdminData,
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    if (!list.content) {
                        $('.noPeople').show();
                    }
                    var obj = {
                        admin_id: admin_id,
                        list: list
                    }
                    $(".replacement").css("display", "block")
                    var list = JSON.parse(data)
                    var template = Handlebars.compile($("#admin_content_tpl").html())
                    var html = template(obj)
                    $("#admin_content").html(html)
                    $("#admin_content select option[value='" + adminId + "']").attr("selected", "selected");
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }, callError: function () {

            }
        })

        $("#changeCommitBtn").on('click', function () {
            if ($("#admin_content div select").val() != '') {
                udpateAdmin.admin_id = $("#admin_content div select").val();
            }
            site.send({
                url: "manager/udpateAdminSalesman.do",
                // async: false,
                data: udpateAdmin,
                callback: function (data) {
                    var list = JSON.parse(data)
                    if (list.type == '1') {
                        $(".replacement").css("display", "none")
                        Constant.fn.Message('T', list.msg);
                        pjaxReload();
                    } else {
                        Constant.fn.Message('F', list.msg);
                    }
                }
            })
        })
    }

    // 查看关联订单
    function selectContactOrder() {
        site.send({
            url: url.selectOrderPageListByPid,
            // async: false,
            data: selectOrderData,
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    $(".associatedOrder").css("display", "block")
                    var list = JSON.parse(data)
                    var template = Handlebars.compile($("#dataList_content_tpl").html())
                    var html = template(list)
                    $("#dataList_content").html(html)

                    $("#dataList_content .orderList").on('click', function () {
                        pjaxGo("loanBefore/orderDetail.html?order_id=" + $(this).data('order_id') + "&product_id=" + $(this).data('product_id') + "&task_id=" + $(this).data('taskId') + "&node_id=" + $(this).data('node_id') + "&s_id=" + $(this).data('s_id'));
                    })
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })
    }

    // 编辑客户
    function selectProductALlFun() {
        site.send({
            url: url.selectProductALl,
            //async:false
            data: selectProductALlData,
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    $(".editProduct_window").show();

                    //初始化弹框内容
                    $("#editSelectType").val('');
                    $("#editSerachContent").val('');

                    $("#total").text(list.content.total)
                    var template = Handlebars.compile($("#productList_content_tpl").html())
                    $("#productList_content").html(template(list))

                    //list点击事件
                    $("#productList_content tr").click(function () {
                        if (selectProductALlData.pid != '') {
                            pjaxGo('customerManager/customerlist/customerEdit.html?pid=' + selectProductALlData.pid + '&productId=' + $(this).data('id') + '')
                        } else {
                            pjaxGo('customerManager/customerlist/customerEdit.html?productId=' + $(this).data('id') + '')
                        }
                    })

                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })
    }

    function onBindFun(type) {
        $('.focus').on('click', function () {
            var _this = this;
            site.send({
                url: url.updatePersonalfollow,
                data: {
                    pid: $(_this).data('pid'),
                    isfollow: $(_this).data('isfollow') === 0 ? 1 : 0
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type === 1) {
                        if ($(_this).hasClass('icon-aixin1')) {
                            $(_this).removeClass('icon-aixin1').addClass('icon-aixin').data('isfollow', 1);
                        } else {
                            $(_this).removeClass('icon-aixin').addClass('icon-aixin1').data('isfollow', 0);
                        }
                    } else {
                        Constant.fn.Message("F", data.msg);
                    }
                }
            })
        })

        //拿到所有的复选框，当有复选框没选上的时候,取消全选
        $("input:checkbox[name='ch_id']").on('click', function () {
            var checkboxs = $("input:checkbox[name='ch_id']");
            var sum = 0;
            var length = checkboxs.length;
            $.each(checkboxs, function (i, checkbox) {
                if ($(checkbox).prop("checked")) {
                    sum++;
                }
            })
            if (sum == length) {
                $('#checkAllOrNot').prop("checked", true);
            } else {
                $('#checkAllOrNot').prop("checked", false);
            }
        })


        // 全选和全不选
        $("#checkAllOrNot").on('click', function () {
            $("input[name='ch_id']").prop("checked", $(this).prop("checked"))
        })

    // select菜单栏的change事件
        $(".custlistSelect").on('change', function () {
            adminId = $(this).data('adminid');
            personId = $(this).data('personalid');
            payee = $(this).data('payee');
            homephone = $(this).data('homephone');
            label_id = $(this).data('label_id');
            var obj = $(this).find("option:selected");
            // 编辑客户
            if (obj.val() == 'editPerson') {
                selectProductALlData = {};
                selectProductALlData.pid = personId;
                selectProductALlData.status = '2';
                selectProductALlFun();

                $(".tabHint").val('-1')
                editpid = personId;
            }
            // 拉黑名单
            if (obj.val() == 'lockPerson') {
                $(".blacklist").css("display", "block")
                $(".tabHint").val('-1')
                block_list.ids = personId;
                $(".block_list_name").text(payee)

            }
            // 更换业务员
            if (obj.val() == 'changeSalesMan') {
                selectAdminData.admin_id = JSON.parse(localStorage.getItem('content')).admin.id;
                udpateAdmin.pid = personId;
                changeAdminFun(adminId);
                $(".tabHint").val('-1')
            }
            //查看关联订单
            if (obj.val() == 'checkReOrder') {
                selectOrderData = {
                    personalId: $(this).data('personalid'),
                    pageNum: 1
                }
                //selectOrderData.personalId = $(this).data('personalid');
                selectContactOrder();
                $(".tabHint").val('-1')
            }
            //查看手机通讯录
            if (obj.val() == 'personalBook') {
                var personalId = personId
                var pageNum = $("#pageNum").val();
                // window.location.href="customerManager/phoneAddressBook/phone_address_book.html?personalId="+personalId+"&pageNum="+pageNum+""
                $(".tabHint").val('-1')
                $(".phone_Book_window").css("display", "block")
                frontData.personalId = personalId;
                frontData.pageNum = pageNum;
                phoneBookList();
            }

            if (obj.val() == 'setLabel') {
                $(".tagSet_window_select option:first").prop('selected', true);
                tagSetId = personId;
                var labelId = label_id ? label_id : '1';
                $(".tagSet_window").css("display", "block")
                $(".tagSet_window_select").val(labelId);
                $(".tabHint").val('-1')
            }
            if (obj.val() == 'personLocation') {
                var pId = personId;
                $(".getAddress_window").css("display", "block")
                $(".tabHint").val('-1')
                $(".map_window_name span").text(payee)
                $(".map_window_phone span").text(homephone)
                getAddressSelect(pId);
            }
            if (obj.val() == 'traceLogs') {
                var pid = personId;
                $(".search_traceLog_username").val("");
                $(".search_traceLog_content").val("");
                $(".trace_log_window").css("display", "block")
                $(".tabHint").val('-1')
                queryTraceLogsdata.personal_id = pid;
                queryTraceLogsList();
            }

            // 黑名单恢复
            if (obj.val() == 'coverUsual') {
                $(".coverUsual_winBox").css("display", "block")
                $(".tabHint").val('-1')
                block_list.ids = personId;
                $(".coverName").text(payee);
            }
        })


        // select菜单栏的change事件
        $(".all_block_list").on('change', function () {
            var obj = $(this).find("option:selected");
            // 编辑客户
            if (obj.val() == '1') {
                var val = $(this).find("option:selected").val();
                // 批量删除
                var inp = $("input[name='ch_id']");//获得所有check按钮
                var count = 0;//计数
                for (var i = 0; i < inp.length; i++) {
                    if (inp[i].checked) {
                        count++;
                        if (count < 2) {
                            block_list.ids = inp[i].value;
                        } else {
                            block_list.ids += ("," + inp[i].value);
                        }
                    }
                }
                if (count != 0) {
                    $(".blacklist").css("display", "block")
                    $(".block_list_name").text("所选")
                    block_list.lockedContent = $(".block_list_content").val();
                    block_list.locked = 2;
                } else {
                    Constant.fn.Message('I', "未选择");
                }
                $(".tabHint").val('-1')
                console.log(block_list)
            }


        })

        $(".operationRecord").on('click', function () {
            site.send({
                url: 'manager/selectPageLogList.do',
                //async:false
                data: {
                    pageNum: 1,
                    Table: 't_order_public',
                    tableId: $(this).data('id')
                },
                callback: function (data) {
                    var list = JSON.parse(data)
                    if (list.type == '1') {
                        var template = Handlebars.compile($("#recordList_content_tpl").html())
                        $("#recordList_content").html(template(list));
                        $(".RecordWinBox").show();
                    }
                }
            })
        })


        $(".icon-upDown").unbind().on('click', function () {
            if(a === 'up'){
                Common.queryList(type,'',1);
                a = 'down'
            }else if(a === 'down'){
                Common.queryList(type,'',2);
                a = 'up';
            }
        })
    }


    // 查询跟踪日志
    function queryTraceLogsList() {
        site.send({
            url: url.d_queryTraceLogsList,
            //async:false
            data: queryTraceLogsdata,
            callback: function (data) {
                var list = JSON.parse(data);
                var source = $("#trace_log_content_tpl").html();
                var template = Handlebars.compile(source);
                var html = template(list);
                $('#trace_log_content').html(html);

                if (list.type == '1') {

                }
                else {
                    Constant.fn.Message('F', list.msg)

                }
                // 分页
                $('.trace-page-container').createPager({
                    current: queryTraceLogsdata.pageNum,
                    total: list.content.total,
                    pageSize: list.content.pageSize,
                    needInput: false,
                    backFn: function (current) {
                        queryTraceLogsdata.pageNum = current;
                        queryTraceLogsList();
                    }
                })

                //删除日志
                $(".delect_trace_log").click(function () {
                    delect_ids.ids = $(this).data("id");
                    delect_trace_log();
                })
                // 编辑日志
                $(".edit_trace_log").click(function () {
                    edit_traceLog.id = $(this).data("id");
                    state = 'edit';
                    newAndEditTraceLogWindow(state, $(this).data("content"));
                })
                //拿到所有的复选框，当有复选框没选上的时候,取消全选
                $("input:checkbox[name='ch_id3']").on('click', function () {
                    var checkboxs = $("input:checkbox[name='ch_id3']");
                    var sum = 0;
                    var length = checkboxs.length;
                    $.each(checkboxs, function (i, checkbox) {
                        if ($(checkbox).prop("checked")) {
                            sum++;
                        }
                    })
                    if (sum == length) {
                        $('#checkAllOrNot3').prop("checked", true);
                    } else {
                        $('#checkAllOrNot3').prop("checked", false);
                    }
                })

                $("#checkAllOrNot3").on('click', function () {

                    $("input[name='ch_id3']").prop("checked", $(this).prop("checked"))

                })
                $(".all_trace_delete").on('change', function () {
                    var obj = $(this).find("option:selected");
                    if (obj.val() == 1) {
                        var inp = $("input[name='ch_id3']");
                        var count = 0;//计数
                        for (var i = 0; i < inp.length; i++) {
                            if (inp[i].checked) {
                                count++;
                                if (count < 2) {
                                    delect_ids.ids = inp[i].value;
                                } else {
                                    delect_ids.ids += ("," + inp[i].value);
                                }
                            }
                        }
                        if (count != 0) {
                            delect_trace_log()
                        } else {
                            Constant.fn.Message('I', "未选择")
                        }


                    }
                    $(".all_trace_delete").val('-1')
                })


            }
        })

    }

    $(".add_trace_log_window_commit").click(function () {
        if (state == 'new') {
            site.send({
                url: url.e_insertTraceLogs,
                //async:false
                data: {
                    personal_id: queryTraceLogsdata.personal_id,
                    logs_type: "5",
                    content: $(".add_trace_log_text").val()
                },
                callback: function (data) {
                    var list = JSON.parse(data);
                    if (list.type == 1) {
                        Constant.fn.Message('T', list.msg)
                        queryTraceLogsdata.content = '';
                        queryTraceLogsList();
                        $(".trace_log_window").css("display", "block")
                        $(".add_trace_log_window").css("display", "none");
                    } else {
                        Constant.fn.Message('F', list.msg)
                    }
                }

            })
        }
        if (state == 'edit') {
            edit_traceLog.content = $(".add_trace_log_text").val();
            site.send({
                url: url.g_editTraceLogs,
                //async:false
                data: edit_traceLog,
                callback: function (data) {
                    var list = JSON.parse(data);
                    if (list.type == 1) {
                        Constant.fn.Message('T', list.msg)
                        queryTraceLogsList();
                        $(".trace_log_window").css("display", "block")
                        $(".add_trace_log_window").css("display", "none");
                    } else {
                        Constant.fn.Message('F', list.msg)
                    }
                }
            })
        }
    })
    //
    $(".add_trace_log_window_cancel").click(function () {
        $(".trace_log_window").css("display", "block")
        $(".add_trace_log_window").css("display", "none");

    })
    //跟踪日志搜索
    $(".search_traceLog_Btn").click(function () {
        queryTraceLogsdata.add_username = $(".search_traceLog_username").val();
        queryTraceLogsdata.content = $(".search_traceLog_content").val();
        queryTraceLogsList();
    })



    var Common = {
        init: function () {
            this.pageNum = 1;

            $(".datepicker").datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                pickerPosition: 'bottom',
            })

            var _this = this;

            site.send({
                url: url.ajaxqueryRegion,
                // async:false,
                data: {parentId: 0},
                callback: function (data) {
                    var list = JSON.parse(data);
                    var source = $("#province_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(list);
                    $('#province_list').html(html);
                }
            })

            $("#province_list").on('change', function () {
                var _this = this;
                if ($(_this).val()) {
                    site.send({
                        url: url.ajaxqueryRegion,
                        // async:false,
                        data: {parentId: $(_this).val()},
                        callback: function (data) {
                            var list = JSON.parse(data);
                            var source = $("#city_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var html = template(list);
                            $('#city_list').html(html);
                        }
                    })
                } else {
                    $("#city_list").html('<option value="" class="" selected="selected">选择市</option>');
                    $("#area_list").html('<option value="" class="" selected="selected">选择区县</option>');
                }
            })

            $("#city_list").on('change', function () {
                var _this = this;
                if ($(_this).val()) {
                    site.send({
                        url: url.ajaxqueryRegion,
                        // async:false,
                        data: {parentId: $(_this).val()},
                        callback: function (data) {
                            var list = JSON.parse(data);
                            var source = $("#area_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var html = template(list);
                            $('#area_list').html(html);
                        }
                    })
                } else {
                    $("#area_list").html('<option value="" class="" selected="selected">选择区县</option>');
                }
            })


            var content = JSON.parse(localStorage.getItem('content'));
            // 角色
            site.send({
                url: url.selectAdminSalesman,
                //async:false
                data: {
                    pageNum: 1,
                    admin_id: content.admin.id
                },
                callback: function (data) {
                    var list = JSON.parse(data);
                    var source2 = $("#salesMan_list_tpl").html();
                    var template2 = Handlebars.compile(source2);
                    var html2 = template2(list.content);
                    $('#salesMan_list').html(html2);
                }
            })

            $(".black_list_commit").click(function () {
                block_list.lockedContent = $(".block_list_content").val();
                block_list.locked = 2;
                block_list_fun();
            })


            $(".cover_commit").click(function () {
                block_list.lockedContent = $(".cover_content").val();
                block_list.locked = 1;
                cover_fun();
            })




        },
        pageNum : 1,
        queryList: function (type, pageNum ,sequence) {
            var _this = this;
            var data = {
                type: type,
                pageNum: pageNum ? pageNum: _this.pageNum
            };

            if ($("#beginTime").val()) {
                data.beginTime = $("#beginTime").val();
            }

            if ($("#endTime").val()) {
                data.endTime = $("#endTime").val();
            }

            if ($("#keyword").val()) {
                data.searchKey = $("#keyword").val();
            }

            if ($("#province_list").val()) {
                data.addrprovince = $("#province_list").val();
            }

            if ($("#city_list").val()) {
                data.addrCity = $("#city_list").val();
            }

            if ($("#area_list").val()) {
                data.addrArea = $("#area_list").val();
            }

            if ($("#salesMan_list").val()) {
                data.adminId = $("#salesMan_list").val();
            }

            if ($("#isFollow").val()) {
                data.isfollow = $("#isFollow").val();
            }

            if (sequence) {
                data.sequence = sequence;
            }

            site.send({
                url: url.list,
                //async:false
                data: data,
                callback: function (data) {
                    var list = JSON.parse(data)
                    if (list.type == '1') {
                        $("#personalTotal").text()
                        var source = $("#personalPublicList_tpl").html();
                        var template = Handlebars.compile(source);

                        var menuIndex = getAurlparam('h') || 0;
                        var thirdMenusIndex = getAurlparam('t') || 0;
                        var leftIndex = getAurlparam('i') || 0;

                        var storageContent = JSON.parse(localStorage.getItem('content'));

                        var obj = {
                            content: list,
                            fourthMenus: storageContent.menus[menuIndex].children[leftIndex].children[thirdMenusIndex].children || {}
                        }

                        var html = template(obj);
                        $('#personalPublicList').html(html);

                        var source = $("#special_fourth_tpl").html()
                        var template = Handlebars.compile(source)
                        var html = template(storageContent.menus[menuIndex].children[leftIndex].children[thirdMenusIndex].children)
                        $(".addCustomerBtn").remove();
                        $('.public-botPage-left').append(html)


                        // 录入订单
                        $(".addCustomerBtn").on('click', function () {
                            personId = ''
                            selectProductALlData = {};
                            selectProductALlData.pid = '';
                            selectProductALlData.status = '1';
                            selectProductALlFun();
                        })


                        if (list.content) {
                            $('.result').html(list.content.total ? list.content.total : '0');
                        }

                        $('.all-page-container').createPager({
                            current: pageNum ? pageNum: _this.pageNum,
                            total: list.content.total,
                            pageSize: list.content.pageSize,
                            needInput: false,
                            backFn: function (current) {
                                _this.pageNum = current;
                                _this.queryList(type);
                            }
                        })


                        Public.record('t_personal_public');
                        onBindFun(type);
                    } else {
                        Constant.fn.Message("F", data.msg);
                    }
                }

            })

        }
    }

    return Common;
})